package com.luoyuanxiangvip.admin.controller.support;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.luoyuanxiangvip.common.annotation.Cache;
import com.luoyuanxiangvip.common.constant.Constant;
import com.luoyuanxiangvip.common.utils.AjaxResult;
import com.luoyuanxiangvip.common.utils.PageUtil;
import com.luoyuanxiangvip.common.vo.support.QueryPage;
import com.luoyuanxiangvip.core.entity.SysUser;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;

/**
 * <p>
 * 公共控制器
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiangvip.com</p>
 * @since 2019/5/26 15:47
 */
public class BaseController<S extends IService<T>, T, ID extends Serializable> {

    @Resource
    protected HttpServletRequest request;
    @Resource
    protected HttpSession session;
    @Autowired
    protected S iService;

    protected S getiService() {
        return iService;
    }

    protected SysUser getUser() {
        return (SysUser) session.getAttribute(Constant.USER);
    }


    @ApiOperation(value = "获取分页列表")
    @PostMapping("/list")
    public AjaxResult list(@RequestBody QueryPage queryPage) {
        IPage<T> page = iService.page(new Page<>(queryPage.getPage(), queryPage.getLimit()));
        return AjaxResult.success("获取分页列表成功", new PageUtil<>(page));
    }

    @ApiOperation(value = "添加或修改")
    @PostMapping("/saveOrUpdate")
    @Cache(value = "【BaseController】添加或修改",flush = true)
    public AjaxResult saveOrUpdate(@RequestBody T entity) {
        return iService.saveOrUpdate(entity) ? AjaxResult.success("添加或修改成功") : AjaxResult.error("添加或修改失败");
    }

    @ApiOperation(value = "获取详情")
    @GetMapping("/info/{id}")
    public AjaxResult info(@PathVariable("id") ID id) {
        return AjaxResult.success("获取详情成功", iService.getById(id));
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("/del/{id}")
    public AjaxResult delete(@PathVariable("id") ID id) {
        return iService.removeById(id) ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }
}
